import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user';
import { Repository, UpdateResult } from 'typeorm';
import { UserStore } from './entities/userSotre';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
  ) {}

  async queryUser(phone: string) {
    const user = await this.userRepository.findOne({
      select: ['id', 'nickname', 'authorImg', 'phone'],
      where: { phone },
    });
    if (!user) {
      return await this.userRepository.save({ phone });
    }
    return user;
  }

  async findOne(phone: string) {
    return await this.userRepository.findOne({
      select: ['id', 'nickname', 'authorImg', 'phone'],
      where: { phone },
    });
  }

  async createStore(storyId: number, userId: number) {
    const query = await this.userRepository.manager
      .getRepository(UserStore)
      .findOne({
        where: {
          storyId,
          userId,
        },
      });
    if (!query) {
      return await this.userRepository.manager.getRepository(UserStore).save({
        storyId,
        userId,
      });
    }
    return null;
  }

  async removeStore(id: any, userId: number) {
    const query = await this.userRepository.manager
      .getRepository(UserStore)
      .findOne({
        where: {
          storyId: id,
          userId,
        },
      });
    if (query) {
      return await this.userRepository.manager
        .getRepository(UserStore)
        .remove(query);
    }
    return null;
  }

  async queryStoreList(useId) {
    return await this.userRepository
      .createQueryBuilder('u')
      .select([
        's.id as id',
        's.title as title',
        'i.image as image',
        's.hint as hint',
      ])
      .leftJoin('user_store', 'us', 'us.userId = u.id')
      .leftJoin('story', 's', 's.id = us.storyId')
      .leftJoin('images', 'i', 'i.storyId = s.id')
      .where('us.userId = :userId', { userId: useId })
      .getRawMany();
  }

  async queryUserUpdate(sub, nickname: string, url: string) {
    let user: UpdateResult;
    try {
      user = await this.userRepository.update(sub, {
        nickname,
        authorImg: url,
      });
    } catch (err) {
      console.log(err);
    }

    return user;
  }
}
